import axios from 'axios';
import moment from 'moment'

//moment 是需要安装的
// npm install moment
// 一次性解决时区和日期格式问题
Date.prototype.toISOString = function () {
    return moment(this).format('YYYY-MM-DD HH:mm:ss')
}
console.log("token:" + localStorage.getItem("Token"));

const config = {
    // baseURL: process.env.baseURL
    baseURL: 'http://82.157.238.181:8106',
    //baseURL: 'http://127.0.0.1:8106',
    //baseURL: 'http://127.0.0.1:8005',
    timeout: 10000,
};

var $http = {};
const instance = axios.create(config);

/**
 * @function post请求
 * @param {*} url  请求地址 不带域名 
 * @param {*} data 请求数据对象
 * @param {*} that 当前页面的this
 * @param {*} callBack 回调函数 function(ret)
 * @returns 
 */
$http.post = async function (url, data, that, callBack) {
    var ret = [];
    await instance({
        method: "POST",
        url: url,
        data: data,
        headers: { 'Content-Type': 'application/json', "token": localStorage.getItem("Token") },
    }).then(response => {
        if (response.data.Code == 2000) {
            ret = response.data;
            if (callBack != undefined) {
                callBack(ret);
            }
        }
        else if (response.data.Code == 4003) {
            that.$Message["error"]({ background: true, duration: 10, content: response.data.Msg });            
            that.$router.push("/Login");
        }
    }).catch(function (error) {
        debugger
        that.$Message["error"]({ background: true, duration: 10, content: "请求回调失败" });
    });
    return ret;
}
/**
 * @function get请求
 */
$http.get = async function (url, data, that) {
    var ret;
    await instance({
        method: "get",
        url: url,
        params: data,
    }).then(response => {
        if (response.data.Code == 2000) {
            ret = response.data.Data;
        }
        else {
            console.log(response.data.Msg);
            that.$Message["error"]({ background: true, duration: 10, content: response.data.Msg });
        }
    })
}
// http response 拦截器
instance.interceptors.response.use(
    response => {
        //拦截响应，做统一处理
        if (response.data.code) {
            // console.log(response.status);
            switch (response.status) {
                case 301:
                    console.log('登录过期');
                // store.state.isLogin = false
                // router.replace({
                //   path: 'login',
                //   query: {
                //     redirect: router.currentRoute.fullPath
                //   }
                // })
            }
        }
        return response
    },
    //接口错误状态处理，也就是说无响应时的处理
    error => {
        return Promise.reject(error.response.status) // 返回接口返回的错误信息
    })

export default $http; 
